package com.chen.servlet;

import com.alibaba.fastjson.JSON;
import com.chen.pojo.Role;
import com.chen.pojo.User;
import com.chen.service.role.RoleService;
import com.chen.service.role.RoleServiceImp;
import com.chen.service.user.UserService;
import com.chen.service.user.UserServiceImp;
import com.chen.util.Constants;
import com.chen.util.PageSupport;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method!=null && "savepwd".equals(method)){
            updatePwd(req, resp);
        }else if (method.equals("pwdmodify")&&method!=null){
            this.pwdmodify(req, resp);
        }else if (method.equals("query")&&method!=null){
            this.query(req, resp);
        }
    }
    protected void updatePwd(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        //从session获取用户id
        Object obj = req.getSession().getAttribute(Constants.USER_SESSION);
        //获取入参中的新密码
        String newpassword = req.getParameter("newpassword");
        if (obj==null || StringUtils.isNullOrEmpty("newpassword")){
            req.setAttribute("message","新密码不可为空~");
        }else {
            UserService userService = new UserServiceImp();
            boolean flag = userService.updatePwd(((User) obj).getId(), newpassword);
            if (flag){
                req.setAttribute("message","密码修改成功，请退出，使用新密码登录~");
                //修改成功，移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message","密码修改失败~");
            }
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
    }
    protected void pwdmodify(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //从session中获取旧密码
        Object obj = req.getSession().getAttribute(Constants.USER_SESSION);
        //获取入参中的旧密码
        String oldpassword = req.getParameter("oldpassword");
        HashMap<String, Object> resultMap = new HashMap<>(16);
        if (obj == null){
            //session过期
            resultMap.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){
            //旧密码输入为空
            resultMap.put("result","error");
        }else {
            if (oldpassword.equals(((User)obj).getUserPassword())){
                //旧密码输入正确JSONString(resultMap));
                //        writer.flush();
                resultMap.put("result","true");
            }else {
                //旧密码输入有误
                resultMap.put("result","false");
            }
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(resultMap));
        writer.close();
    }
    protected void query(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        //获取入参
        String queryName = req.getParameter("queryname");
        String temp = req.getParameter("temp");
        String pageIndex = req.getParameter("pageIndex");
        //角色
        int queryUserRole = 0;
        //每页最大容量可前端传入，也可写成配置项，这里暂时写死
        int pageSize = 5;
        int currentPageNo = 1;
        //参数处理
        if (temp != null && temp.length()>0){
            queryUserRole = Integer.parseInt(temp);
        }
        if (pageIndex != null && pageIndex.length()>0){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        UserService userService = new UserServiceImp();
        //获取用户总数（上一页，下一页）
        int totalCount = userService.getUserCount(queryName, queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        int totalPageCount = pageSupport.getTotalPageCount();
        //控制首页和尾页
        if (currentPageNo<0){
            currentPageNo = 0;
        }else if (currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;
        }
        //查询用户列表
        List<User> userList = userService.getUserList(queryName, queryUserRole, currentPageNo, pageSize);
        //获取角色列表
        RoleService roleService = new RoleServiceImp();
        List<Role> roleList = roleService.getRoleList();

        req.setAttribute("userList",userList);
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryName);
        req.setAttribute("queryUserRole",queryUserRole);

        req.getRequestDispatcher("userlist.jsp").forward(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
